<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>产品管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi" />
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
    <link rel="stylesheet" href="./css/font.css">
    <link rel="stylesheet" href="./css/xadmin.css">
    <link rel="stylesheet" href="lib/layui/css/layui.css">
    <link rel="stylesheet" href="css/simditor.css">
    <script src="js/jquery-3.5.1.min.js"></script>
    <script src="js/jquery.form.js"></script>
    <script type="text/javascript" src="lib/layui/layui.js" charset="utf-8"></script>
    <script type="text/javascript" src="./js/xadmin.js"></script>
    <script type="text/javascript" src="js/module.js"></script>
    <script type="text/javascript" src="js/hotkeys.js"></script>
    <script type="text/javascript" src="js/uploader.js"></script>
    <script type="text/javascript" src="js/simditor.js"></script>
    <!-- 让IE8/9支持媒体查询，从而兼容栅格 -->
    <!--[if lt IE 9]>
    <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
    <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>

<body class="layui-anim layui-anim-up">
<div class="x-nav">
      <span class="layui-breadcrumb">
        <a href="">首页</a>
        <a href="">演示</a>
        <a>
          <cite>导航元素</cite></a>
      </span>
    <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right" href="javascript:location.replace(location.href);" title="刷新">
        <i class="layui-icon" style="line-height:30px">ဂ</i></a>
</div>

<!--搜索-->
<div class="demoTable">
    产品名称：
    <div class="layui-inline">
        <input  name="product_name" class="layui-input" id="demoName" autocomplete="off">
    </div>
    产品ID：
    <div class="layui-inline">
        <input  name="product_id" class="layui-input" id="demoId" autocomplete="off">
    </div>
    <button class="layui-btn layui-icon layui-icon-search" data-type="reload">搜索</button>
</div>
<!--搜索结束-->

<!--数据表格-->
<table class="layui-hide" id="test" lay-filter="test"></table>

<!--详情弹框的数据表格-->
<div id="openProductBox" style="display: none; padding: 10px;">
    <table id="openProductTable" lay-filter="openProductTable"></table>
</div>


<!--头工具栏-->
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>
        <button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>
        <button class="layui-btn layui-btn-sm" lay-event="isAll">验证是否全选</button>
        <button class="layui-btn layui-btn-sm layui-icon" lay-event="add" lay-filter="addLayer">&#xe654;</button>
        <!--<button class="layui-btn layui-btn-sm layui-icon" lay-event="add">&#xe654;</button>
        <button class="layui-btn layui-btn-sm layui-icon" lay-event="batchDel">&#xe640;</button>
        <button class="layui-btn layui-btn-sm layui-icon" lay-event="flush">&#xe669;</button>-->
    </div>
</script>


<!--添加或修改产品的弹框-->
<div style="display: none;" id="addF">
    <form action="" class="layui-form" lay-filter="dataFrm" id="dataFrm">
        <div class="layui-form-item">
                <label class="layui-form-label">品类ID</label>
                <div class="layui-input-inline">
                    <input type="text" name="category_id" lay-verify="required" autocomplete="off" class="layui-input" placeholder="请输入品类ID">
                </div>
                <!--<label class="layui-form-label">商品ID</label>
                <div class="layui-input-inline">
                    <input type="text" name="id" lay-verify="required" autocomplete="off" class="layui-input">
                </div>-->
        </div>
        <div class="layui-form-item">
                <label class="layui-form-label">名称</label>
                <div class="layui-input-inline">
                    <input type="text" name="name" lay-verify="required" autocomplete="off" class="layui-input" placeholder="请输入名称">
                </div>
                <label class="layui-form-label">备注</label>
                <div class="layui-input-inline">
                    <input type="text" name="subtitle" lay-verify="required" autocomplete="off" class="layui-input" placeholder="请添加备注">
                </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">主图</label>
                <div class="layui-input-inline">
                    <!--<input type="text" name="main_image" lay-verify="required" autocomplete="off" class="layui-input">-->
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">子图</label>
                <div class="layui-input-inline">
                    <!--<input type="text" name="subImages" lay-verify="required" autocomplete="off" class="layui-input">-->
                </div>
            </div>
        </div>
        <div class="layui-form-item">
                <label class="layui-form-label">价格</label>
                <div class="layui-input-inline">
                    <input type="text" name="price" lay-verify="required" autocomplete="off" class="layui-input" placeholder="请输入价格">
                </div>
                 <label class="layui-form-label">库存</label>
                <div class="layui-input-inline">
                     <input type="text" name="stock" lay-verify="required" autocomplete="off" class="layui-input" placeholder="请输入库存量">
                 </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">状态</label>
                <div class="layui-input-block">
                    <input type="radio" name="status" value="上架" title="上架" checked="">
                    <input type="radio" name="status" value="下架" title="下架">
                </div>
            </div>
        </div>
        <div class="layui-form-item" style="text-align: center;">
            <div class="layui-input-block">
                <button type="button" class="layui-btn layui-icon layui-icon-release" lay-filter="add" lay-submit="">提交</button>
                <button type="reset" class="layui-btn layui-icon layui-icon-refresh">重置</button>
            </div>
        </div>
    </form>
    <!--上传图片-->
    <form action="http://localhost:8080/shopping/manage/product?type=upload" method="post" target="_self" enctype="multipart/form-data" id="upImg" style="position: absolute;top: 110px;left: 110px">
        <input type="file"  name="upload_file"/>
        <br/>
        <input type="submit" value="上传" />
    </form>
    <form action="http://localhost:8080/shopping/manage/product?type=upload" method="post" enctype="multipart/form-data" id="upImgSon" style="position: absolute;top: 170px;left: 110px">
        <input type="file"  name="upload_file"/>
        <br/>
        <input type="submit" value="上传" />
    </form>
</div>


<!--修改富文本的弹框-->
<div style="display: none;" id="changeF">
    <form action="" class="layui-form" lay-filter="dataFrm" id="dataCrm">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">商品ID</label>
                <div class="layui-input-inline">
                    <input type="text" name="product_id" lay-verify="required" autocomplete="off" class="layui-input">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">详细描述</label>
                <div class="layui-input-block">
                    <textarea id="editor" autofocus></textarea>
                    <button id="btn" class="layui-btn" type="button">提交</button>
                </div>
            </div>
        </div>
        <div class="layui-form-item" style="text-align: center;">
            <div class="layui-input-block">
                <button type="button" class="layui-btn layui-icon layui-icon-release" lay-filter="fwb" lay-submit="">提交</button>
                <button type="reset" class="layui-btn layui-icon layui-icon-refresh">重置</button>
            </div>
        </div>
    </form>
</div>

<!--操作列-->
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="detail">查看</a>
    <a class="layui-btn layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-xs" lay-event="fu">详情</a>
</script>



<!--主图片模板-->
<script type="text/html" id="imgtmp">
    <img src="{{'http://localhost:8080/pic/'+d.main_image}}" style="height: 100%;white-space: normal;">
</script>

<!--子图片模板-->
<script type="text/html" id="imgSon">
    <img src="{{'http://localhost:8080/pic/'+d.main_image}}" style="height: 100%;white-space: normal;">
</script>


<script>
    layui.use(['table','layer','form'], function(){
        var table = layui.table,
            layer = layui.layer;
        form = layui.form;
        var $ = layui.$;

        /*产品列表的渲染*/
        table.render({
            elem: '#test'
            ,url:'http://localhost:8080/shopping/manage/product?type=list'  //换
            //,url:'data.json'
            ,parseData: function(res){ //res 即为原始返回的数据
                console.log(res)
                return {
                    "code": res.status, //解析接口状态
                    //"count": res.data.length, //解析数据长度
                    "data": res.data, //解析数据列表
                    "count": res.count, //解析数据长度
                };
            }

            ,response: {
                dataName: 'data' //规定数据状态的字段名称，默认：code
                //,statusCode: 0 //规定成功的状态码，默认：0
                //,countName: 'total' //规定数据总数的字段名称，默认：count

            }

            ,request: {
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
                ,pageName: 'pageNum' //页码的参数名称，默认：page
            }

            ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: ['filter', 'exports', 'print']
            ,title: '产品列表'
            ,cols: [[
                {type: 'checkbox', fixed: 'left'}
                ,{field:'id', title:'编号', sort: true,align:'center'}
                ,{field:'category_id', title:'种类编号', edit: 'text',align:'center'}
                ,{field:'name', title:'名称',  edit: 'text', align:'center'}
                ,{field:'subtitle', title:'备注' , edit: 'text',align:'center'}
                ,{field:'main_image', title:'主图' , align:'center',templet:"#imgtmp"}
                ,{field:'status', title:'状态', edit:'text', align:'center',templet:function (d) {
                        let state = "";
                        if(d.status === 1){
                            state = "<input type='checkbox' value='" + d.id + "' id='status' lay-filter='stat' checked='checked' name='status'  lay-skin='switch' lay-text='上架|下架' >";
                        }
                        else {
                            state = "<input type='checkbox' value='" + d.id + "' id='status' lay-filter='stat'  name='status'  lay-skin='switch' lay-text='上架|下架' >";
                        }
                        return state
                    }}
                ,{field: 'price', title:'价格',align:'center'}
                ,{fixed: 'right', title:'操作', align:'center', toolbar: '#barDemo'}
            ]]
            ,page: true
            ,id:'testReload'
        });

/*产品搜索重载数据表格*/
        var $ = layui.$, active = {
            reload: function(){
                var demoName = $('#demoName').val()
                var demoId = $('#demoId').val()
                console.log(demoName,demoId)
                //执行重载
                table.reload('testReload', {
                    url:'http://localhost:8080/shopping/manage/product?type=search'  //搜索的url
                    ,page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where: {
                        product_name:demoName,
                        product_id:demoId
                    }
                }, 'data');
            }
        };

        $('.demoTable .layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });


        //监听开关事件
        form.on('switch(stat)', function (data) {
            var contexts;
            var sta;
            var x = data.elem.checked;//判断开关状态
            product_id = data.value
            if (x === true) {
                contexts = "上架";
                sta=1;
            } else {
                contexts = "下架";
                sta=2;
            }
            console.log(product_id,sta)
            //自定义弹窗
            layer.open({
                content: "你确定要将商品"+contexts+"吗?"
                , btn: ['确定', '取消']
                , yes: function (index, layero) {
                    //按钮确定【按钮一】的回调
                    data.elem.checked = x;
                    //对商品进行上架或下架处理
                    $.ajax({
                        type:'POST',
                        //url:'data.json',
                        url: 'http://localhost:8080/shopping/manage/product?type=set_sale_status',
                        dataType:'json',
                        xhrFields: { withCredentials: true },
                        data: {
                            //上下架的参数
                            "product_id": product_id,
                            "status":sta
                        },
                        success: function (data) {
                            if (data.status === 0) {
                                layer.msg('产品状态修改成功!');
                                // 数据重载
                                //active.reload();
                                table.render({
                                    elem: '#test'
                                    ,url:'http://localhost:8080/shopping/manage/product?type=list'  //换
                                    //,url:'data.json'
                                    ,parseData: function(res){ //res 即为原始返回的数据
                                        console.log(res)
                                        return {
                                            "code": res.status, //解析接口状态
                                            //"count": res.data.length, //解析数据长度
                                            "data": res.data, //解析数据列表
                                            "count": res.count, //解析数据长度
                                        };
                                    }

                                    ,response: {
                                        dataName: 'data' //规定数据状态的字段名称，默认：code
                                        //,statusCode: 0 //规定成功的状态码，默认：0
                                        //,countName: 'total' //规定数据总数的字段名称，默认：count

                                    }

                                    ,request: {
                                        limitName: 'pageSize' //每页数据量的参数名，默认：limit
                                        ,pageName: 'pageNum' //页码的参数名称，默认：page
                                    }

                                    ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
                                    ,defaultToolbar: ['filter', 'exports', 'print']
                                    ,title: '产品列表'
                                    ,cols: [[
                                        {type: 'checkbox', fixed: 'left'}
                                        ,{field:'id', title:'编号', sort: true,align:'center'}
                                        ,{field:'category_id', title:'种类编号', edit: 'text',align:'center'}
                                        ,{field:'name', title:'名称',  edit: 'text', align:'center'}
                                        ,{field:'subtitle', title:'备注' , edit: 'text',align:'center'}
                                        ,{field:'main_image', title:'主图' , align:'center',templet:"#imgtmp"}
                                        ,{field:'status', title:'状态', edit:'text', align:'center',templet:function (d) {
                                                let state = "";
                                                if(d.status === 1){
                                                    state = "<input type='checkbox' value='" + d.id + "' id='status' lay-filter='stat' checked='checked' name='status'  lay-skin='switch' lay-text='开启|关闭' >";
                                                }
                                                else {
                                                    state = "<input type='checkbox' value='" + d.id + "' id='status' lay-filter='stat'  name='status'  lay-skin='switch' lay-text='开启|关闭' >";
                                                }
                                                return state
                                            }}
                                        ,{field: 'price', title:'价格',align:'center'}
                                        ,{fixed: 'right', title:'操作', align:'center', toolbar: '#barDemo'}
                                    ]]
                                    ,page: true
                                    ,id:'testReload'
                                });
                            }
                        }
                    });
                    form.render();
                    layer.close(index);

                }
                , btn2: function (index, layero) {
                    //按钮【按钮二】的回调
                    data.elem.checked = !x;
                    form.render();
                    layer.close(index);
                    //return false 开启该代码可禁止点击该按钮关闭
                }
                , cancel: function () {
                    //右上角关闭回调
                    data.elem.checked = !x;
                    form.render();
                    // return false; //开启该代码可禁止点击该按钮关闭
                }
            });
            return false;
        });



        let imgUrl
        //接口返回的图片地址
        $(function () {
            $('#upImg').ajaxForm(function (res) {
                var obj = JSON.parse(res)
                console.log(obj.status)
                if(obj.status === 0)
                {
                    imgUrl = obj.data
                    console.log(imgUrl)
                }
                else{
                    console.log("错误")
                }
            })
        })

        let imgUrlSon
        //接口返回的子图地址
        $(function () {
            $('#upImgSon').ajaxForm(function (res) {
                var obj = JSON.parse(res)
                console.log(obj.status)
                if(obj.status === 0)
                {
                    imgUrlSon = obj.data
                    console.log(imgUrlSon)
                }
                else{
                    console.log("错误")
                }
            })
        })

        /*富文本*/
        $(function () {
            var editor = new Simditor({
                textarea: $('#editor')
                //optional options
            });
            $("#btn").click(function () {
                value = editor.getValue()
                console.log(value)
            })
        })


        //头工具栏事件
        table.on('toolbar(test)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'getCheckData':
                    var data = checkStatus.data;
                    layer.alert(JSON.stringify(data));
                    break;
                case 'getCheckLength':
                    var data = checkStatus.data;
                    layer.msg('选中了：'+ data.length + ' 个');
                    break;
                case 'isAll':
                    layer.msg(checkStatus.isAll ? '全选': '未全选');
                    break;
                case 'add':
                    openAdd();
                    break;
            }
        });

        let p='/shopping/manage/product?type=save'

        //打开弹出框
        function openAdd(){
            layer.open({
                type:1,
                title:'新增产品',
                area:['800px','450px'],
                content:$('#addF')
            })
        }

        form.on('submit(add)',function(data){
            let  aa = JSON.stringify(data.field)
            var oj = JSON.parse(aa)
            let category_id = oj.category_id
            let name = oj.name
            let subtitle = oj.subtitle
            //let main_image = oj.main_image
            //let subImages = oj.subImages
            //let detail=oj.detail
            let price = oj.price
            let stock = oj.stock
            let status = oj.status
            let zt
            if(status === '上架')
            {
                zt =1
            }
            else{
                zt =2
            }
            //let id = oj.id
            console.log(category_id,name,subtitle,imgUrl,price,stock,zt)
            $.ajax({
                type:'POST',
                url:'http://localhost:8080'+p,
                dataType:'json',
                xhrFields: { withCredentials: true },
                data:{'category_id':category_id,'name':name,'subtitle':subtitle,'main_image':imgUrl,'subImages':imgUrlSon,'price':price,'stock':stock,'status':zt},
                success:function (res) {
                    if(res.status === 0){
                        layer.msg("添加成功！")
                    }else {
                        layer.msg("添加失败！")
                    }
                }
            })
            return false;
        }),


            //监听工具行
            table.on('tool(test)',function (obj) {
                var data = obj.data //获得当前行数据
                    ,layEvent = obj.event;
                if(layEvent === 'edit'){
                    updateChange();
                }
                /*查看产品详情*/
                else if(layEvent === 'detail'){
                    let product_id = data["id"]
                    console.log(product_id)
                    layer.open({
                        type:1,
                        title:"产品详情",
                        area:["1300px","150px"],
                        content:$('#openProductBox'),
                        success:function (index,layero) {
                            table.render({
                                elem:'#openProductTable'
                                //,url:'data.json'
                                ,url:'http://localhost:8080/shopping/manage/product?type=detail'
                                ,where: {"product_id": product_id}
                                ,parseData: function(res){ //res 即为原始返回的数据
                                    console.log(res)
                                    return {
                                    "code": res.status, //解析接口状态
                                    //"count": res.data.length, //解析数据长度
                                    "data": res.data //解析数据列表
                                    };
                                }
                                ,response: {
                                dataName: 'data' //规定数据状态的字段名称，默认：code
                                //,statusCode: 0 //规定成功的状态码，默认：0
                                //,countName: 'total' //规定数据总数的字段名称，默认：count
                                 }
                                ,page:false
                                ,cols:[[
                                    {field:'id', title:'编号', sort: true,align:'center'}
                                    ,{field:'category_id', title:'种类编号', align:'center'}
                                    ,{field:'name', title:'名称',   align:'center'}
                                    ,{field:'subtitle', title:'备注' , align:'center'}
                                    ,{field:'main_image', title:'图片' , align:'center',templet:"#imgtmp"}
                                    ,{field:'sub_images', title:'子图' , align:'center',templet:"#imgSon"}
                                    ,{field:'detail', title:'详细介绍' , align:'center'}
                                    ,{field: 'price', title:'价格',align:'center'}
                                    ,{field: 'stock', title:'库存',align:'center'}
                                    ,{field:'status', title:'状态',  align:'center',templet:function (d) {
                                            if(d.status === 1){
                                                return '上架'
                                            }
                                            else {
                                                return '已下架'
                                            }
                                        }}
                                    ,{field: 'create_time', title:'创建时间',align:'center'}
                                ]]
                                })
                        }
                    })
                }

                else if(layEvent === 'fu'){
                    layer.open({
                        type:1,
                        title:"修改产品详情",
                        area:['900px','500px'],
                        content:$('#changeF'),
                    })
                }
            });

        function updateChange(data) {
            layer.open({
                type:1,
                title:'修改产品',
                area:['800px','450px'],
                content:$('#addF'),
                success:function (index) {
                    form.val("dataFrm",data)
                }
            })
        }

        form.on('submit(fwb)',function (data) {
            let  aa = JSON.stringify(data.field)
            var oj = JSON.parse(aa)
            let product_id = oj.product_id
            console.log(product_id,value)
            $.ajax({
                type:'POST',
                url:'http://localhost:8080/shopping/manage/product?type=richtext_img_upload',
                dataType:'json',
                xhrFields: { withCredentials: true },
                data:{'product_id':product_id,'detail':value},
                success:function (res) {
                    if(res.status === 0){
                        layer.msg("添加成功！")
                    }else {
                        layer.msg("添加失败！")
                    }
                }
            })
        })

    });
        

</script>



</body>
</html>